package com.code.refactoring.重构demo.状态机扭转.stateProcessor;

/**
 * @author wangxi03 created on 2021/4/29 10:32 上午
 * @version v1.0
 */

import com.code.refactoring.重构demo.状态机扭转.check.CheckerExecutor;
import com.code.refactoring.重构demo.状态机扭转.entity.ServiceResult;
import com.code.refactoring.重构demo.状态机扭转.entity.StateContext;

import javax.annotation.Resource;

/**
 * 状态机处理器模板类
 */

public abstract class AbstractStateTemplateProcessor<T, C> implements StateProcessor<T, C>, StateActionStep<T, C> {

    @Resource
    private CheckerExecutor<T, C> checkerExecutor;

    @Override
    public final ServiceResult<T> action(StateContext<C> context) throws Exception {
        ServiceResult<T> result = null;
        try {
            // 参数校验器
            result = checkerExecutor.paramCheck(getCheckable(context).getParamChecker(), context);
            if (!result.isSuccess()) {
                return result;
            }
            // 数据准备
            this.prepare(context);
            // 串行校验器
            result = checkerExecutor.serialCheck(getCheckable(context).getSyncChecker(), context);
            if (!result.isSuccess()) {
                return result;
            }
            // 参数校验器
            // getNextState不能在prepare前，因为有的nextState是根据prepare中的数据转换而来
            String nextState = this.getNextState(context);
            // 业务逻辑
            result = this.action(nextState, context);
            // 并行校验器
            result = checkerExecutor.parallelCheck(getCheckable(context).getAsyncChecker(), context);
            if (!result.isSuccess()) {
                return result;
            }
            // 持久化
            result = this.save(nextState, context);
            if (!result.isSuccess()) {
                return result;
            }
            // after
            this.after(context);
            return result;
        } catch (Exception e) {
            throw e;
        }
    }


}
